import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch, Link, } from "react-router-dom";
import { createForm } from 'rc-form';
import { Layout, Empty, Tag, Card, Icon, Button, Divider, message, Skeleton } from "antd";
import { Calendar, WingBlank, WhiteSpace, List, InputItem, Flex, ActivityIndicator, Picker, PullToRefresh } from 'antd-mobile';
import {
    getUpAndDownDeviceMessageApi
} from "../js/api.js";
import zhCN from 'antd-mobile/lib/calendar/locale/zh_CN';
import '../css/wechatmobile.css';
import md5 from 'md5';
import moment from 'moment';
import $ from 'jquery';
const echarts = require('echarts');


class WeChatUpAndDownDevice extends Component {

    constructor(props) {
        super(props);
        this.state = {
        };
    }




    render() {
        return (
            <Router basename="wechatupanddowndevice">
                <Layout style={{ backgroundColor: '#f5f5f5' }}>
                    <Layout.Content>
                        <Route path="/" component={WeChatUpAndDownDeviceMain} />
                    </Layout.Content>
                </Layout>
            </Router>
        );
    }
}

class WeChatUpAndDownDeviceMain extends Component {
    constructor(props) {
        super(props);
        this.state = {
            listLoading: true,
            listData: [],
            currentListData: [],
            // departmentId: this.getUrlParam("departmentId"),
            departmentId: 4,
            chartLoading: true,
            chartData: {
                d: [],
                startTime: undefined
            },
            positionOption: {
                'FF': '顶部',
                '00': '底部',
                '55': '中间'
            },

            refreshing: false,
        }

    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            listLoading: true,
            chartLoading: true,
        });
        let listData = [];
        let currentListData = [];
        getUpAndDownDeviceMessageApi(parseInt(this.state.departmentId))
            .then((res) => {
                res.data.table.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    listData.push({
                        key: index + 1,
                        deviceId: item.deviceId,
                        name: item.name,
                        address: item.address,
                        position: item.position,
                        datetime: item.datetime,
                        alertType: item.alert_type,
                    });
                });

                if (listData.length > 5) {
                    currentListData = listData.slice(0, 5);
                } else {
                    currentListData = listData.slice(0, listData.length);
                }

                this.setState({
                    listData: listData,
                    currentListData: currentListData,
                    chartData: res.data.chartData,
                    listLoading: false,
                    chartLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    listRefresh = () => {
        this.setState({ refreshing: true });
        let listData = [...this.state.listData];
        let currentListData = [...this.state.currentListData];
        setTimeout(() => {
            if (listData.length == currentListData.length) {
                message.info('已经是最后一条数据');
            } else if (listData.length - currentListData.length <= 5) {
                this.setState({ currentListData: listData });
            } else {
                this.setState({
                    currentListData: currentListData.concat(...[listData.slice(currentListData.length, currentListData.length + 5)])
                }, () => { console.log(this.state.currentListData.length) })
            }
            this.setState({ refreshing: false });
        }, 500);
    }

    render() {

        let cardList;
        if (this.state.currentListData.length != 0) {
            cardList = this.state.currentListData.map((value, index) => {
                let content = [{
                    title: '设备名称',
                    value: (<div>{value.name}</div>)
                }, {
                    title: '设备地址',
                    value: (<div>{value.address}</div>)
                }, {
                    title: '升降状态',
                    value: (<div>{this.state.positionOption[value.position]}</div>)
                }, {
                    title: '报警状态',
                    value: (<div>{value.alertType}</div>)
                }];

                let contentCard = content.map((d, index) =>
                    <Card
                        size="small"
                        title={d.title}
                        headStyle={{ padding: '0 8px' }}
                        bodyStyle={{ height: 38, padding: 8 }}
                        className='upAndDownInnerCardHalf'>
                        {d.value}
                    </Card>
                );

                contentCard.push(
                    <Card
                        size="small"
                        title='最近记录时间'
                        headStyle={{ padding: '0 8px' }}
                        bodyStyle={{ height: 38, padding: 8 }}
                        style={{ width: '100%' }}
                        className='upAndDownInnerCardHalf'>
                        {value.datetime}
                    </Card>
                )

                return (
                    <Card
                        className='conditionCard'
                        headStyle={{ padding: '0 16px' }}
                        bodyStyle={{ padding: '10px' }}
                        title={(
                            <span>
                                设备编号:
                                <span style={{ fontSize: 14, }}>{' ' + value.deviceId}</span>
                            </span>
                        )}>
                        <Flex
                            justify="between"
                            wrap='wrap'
                            style={{ marginBottom: '-8px' }}>
                            {contentCard}
                        </Flex>
                    </Card>
                )
            });
        } else {
            cardList = (<Empty />);
        }

        return (
            <div>
                <PullToRefresh
                    style={{
                        height: document.documentElement.scrollHeight,
                        overflow: 'auto',
                    }}
                    damping={60}
                    ref={el => this.ptr = el}
                    indicator={{ deactivate: '上拉可以刷新', }}
                    direction={'up'}
                    refreshing={this.state.refreshing}
                    onRefresh={this.listRefresh}>


                    <Divider>数据有关图表</Divider>
                    <div style={{
                        marginTop: 12,
                        padding: 8,
                        width: '100%',
                        height: 300,
                        backgroundColor: '#fff'
                    }}>
                        <Skeleton loading={this.state.chartLoading} active>
                            {this.state.chartData.d.length == 0 ? (
                                <Empty
                                    image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                                    imageStyle={{
                                        marginTop: 50,
                                    }}
                                    description={
                                        <span style={{ color: '#7a7a7a' }}>
                                            暂无数据
                                        </span>
                                    }
                                />
                            ) : (<ChartUpAndDownDevice chartData={this.state.chartData} />)}
                        </Skeleton>
                    </div>

                    {this.state.listLoading ?
                        (
                            <ActivityIndicator toast text="加载中..." />
                        ) :
                        (
                            <div>
                                <Divider>数据列表</Divider>
                                {cardList}
                            </div>
                        )
                    }
                </PullToRefresh>
            </div>
        )

    }
}

class ChartUpAndDownDevice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
            typesColor: {
                'FF': '#7b9ce1',
                '00': '#bd6d6c',
                '55': '#75d874',
            },
            types: {
                'FF': '顶部',
                '00': '底部',
                '55': '中间',
            },
        };
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartUpAndDownDevice'));

            let dataZoom;

            if (Math.floor(new Date().getTime() - this.state.chartData.startTime) / (24 * 3600 * 1000) <= 3) {
                dataZoom = [{
                    type: 'inside',
                    filterMode: 'weakFilter',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    },
                    filterMode: 'weakFilter',
                    labelFormatter: ''
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    filterMode: 'weakFilter',
                    start: (new Date().getTime() - (3 * 24 * 3600 * 1000) - this.state.chartData.startTime) /
                        (new Date().getTime() - this.state.chartData.startTime) * 100,
                    end: 100,
                }, {
                    start: (new Date().getTime() - (3 * 24 * 3600 * 1000) - this.state.chartData.startTime) /
                        (new Date().getTime() - this.state.chartData.startTime) * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    },
                    filterMode: 'weakFilter',
                    labelFormatter: ''
                }];
            }

            let data = [];
            let categories = [];

            for (let i = 0; i < this.state.chartData.d.length; i++) {
                let name = this.state.chartData.d[i].name;
                if (name.length > 4) {
                    name = name.slice(0, Math.floor(name.length / 2) - 1) + '\n' + name.slice(Math.floor(name.length / 2))
                }
                categories.push(name);

                for (let j = 0; j < this.state.chartData.d[i].position.length; j++) {
                    data.push({
                        name: this.state.chartData.d[i].name,
                        value: [
                            i,
                            this.state.chartData.d[i].time[j][0],
                            this.state.chartData.d[i].time[j][1],
                            this.state.types[this.state.chartData.d[i].position[j]],
                        ],
                        itemStyle: {
                            normal: {
                                color: this.state.typesColor[this.state.chartData.d[i].position[j]]
                            }
                        }
                    });
                }
            }

            chart.setOption({
                title: {
                    text: '防撞柱状态变化展示图',
                    left: 'center'
                },
                tooltip: {
                    confine: true,
                    triggerOn: 'mousemove',
                    formatter: function (params) {
                        return params.marker + '<br>'
                            + '时间段: ' + moment(params.value[1]).format("YYYY-MM-DD HH:mm:ss") + ' ~ '
                            + moment(params.value[2]).format("HH:mm:ss") + '<br>'
                            + '状态: ' + params.value[3];
                    }
                },
                color: ['#7b9ce1', '#bd6d6c', '#75d874'],
                legend: {
                    data: ['顶部', '底部', '中间'],
                    top: 30,
                    selectedMode: false,
                },
                grid: {
                    left: '0px',
                    right: '30px',
                    bottom: '45px',
                    top: '50px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                    }
                },
                xAxis: {
                    min: this.state.chartData.startTime,
                    scale: true,
                    axisLabel: {
                        formatter: function (val) {
                            return moment(val).format("YYYY-MM-DD[\n]HH:mm:ss");
                        }
                    },
                    minInterval: 24 * 3600 * 1000,
                    splitNumber: 3
                },
                yAxis: {
                    name: '设备名称',
                    data: categories
                },
                dataZoom: dataZoom,
                series: [{
                    type: 'custom',
                    name: '顶部',
                    renderItem: (params, api) => this.renderItem(params, api),
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: data,
                }, {
                    type: 'custom',
                    name: '底部',
                }, {
                    type: 'custom',
                    name: '中间',
                }],
            });
            window.onresize = chart.resize;
        }
    }

    renderItem = (params, api) => {
        let categoryIndex = api.value(0);
        let start = api.coord([api.value(1), categoryIndex]);
        let end = api.coord([api.value(2), categoryIndex]);
        let height = 40;

        let rectShape = echarts.graphic.clipRectByRect({
            x: start[0],
            y: start[1] - height / 2,
            width: end[0] - start[0],
            height: height
        }, {
            x: params.coordSys.x,
            y: params.coordSys.y,
            width: params.coordSys.width,
            height: params.coordSys.height
        });
        return rectShape && {
            type: 'rect',
            shape: rectShape,
            style: api.style()
        };
    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartUpAndDownDevice' style={chartStyle} />)
    }
}


export default WeChatUpAndDownDevice;

















